package com.cskaoyan.app.config;

import com.cskaoyan.app.bean.common.Captcha;
import lombok.Data;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Component
@Data
public class CaptchaManager {
    Map<String, Captcha> captchaMap = new HashMap<>();

    public String add(String mobile, int codeLen) {
        Random random = new Random();
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < codeLen; i++) {
            int num = random.nextInt(10);
            buffer.append(num);
        }
        String code = buffer.toString();
        Captcha captcha = new Captcha(code,
                new Date(System.currentTimeMillis() + 5 * 60 * 1000));
        captchaMap.put(mobile, captcha);
        return code;
    }

    public String get(String mobile) {
        Captcha captcha = captchaMap.get(mobile);
        String code = null;
        if (captcha != null) {
            if (captcha.isValid()) {
                code = captcha.getCode();
            } else {
                // 取出时发现失效就删掉
                captchaMap.remove(mobile);
            }
        }
        return code;
    }

    public boolean allow(String mobile) {
        boolean allow = true;
        Captcha captcha = captchaMap.get(mobile);
        if (captcha != null && captcha.isValid()) {
            Date endTime = captcha.getEndTime();
            if (new Date(System.currentTimeMillis() + 4 * 60 * 1000).before(endTime)) {
                return false;
            }
        }
        return allow;
    }
}
